﻿using CoreModule;
using CoreModule.Storages;
using LiveCharts;
using LiveCharts.Defaults;
using LiveCharts.Wpf;
using System;
using System.ComponentModel;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Media.Effects;
using System.Windows.Threading;
namespace IdResourceModule.Views
{
    /// <summary>
    /// ChartGenderControl.xaml 的交互逻辑
    /// </summary>
    public partial class ChartGenderControl : UserControl, INotifyPropertyChanged
    {
        CoreModule.Storages.DbStorage DbStorage { get; set; }
        public ChartGenderControl(CoreModule.Storages.DbStorage dbStorage, IDeviceManager deviceManager)
        {
            InitializeComponent();
            DbStorage = dbStorage;
            DataContext = this;
            try
            {
                this.RefreshData();
            } catch (Exception e)
            {
            }
            deviceManager.MeasurementResultCompletedInManagementModule += DeviceManager_MeasurementResultCompletedInManagementModule;
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void DeviceManager_MeasurementResultCompletedInManagementModule(object sender, MeasurementResultInfoEventArgs e)
        {
            RefreshData();
        }
        public SeriesCollection SeriesCollection { get; set; }
        public string ToolTipText { get; set; }
        public object SelectedItem { get; set; }
        private int total = 0;
        private int manCount;
        public int ManCount
        {
            get { return manCount; }
            set { manCount = value; OnPropertyChanged(nameof(ManCount)); OnPropertyChanged(nameof(ManPercent)); }
        }
        public string ManPercent
        {
            get { return $"{(manCount * 1.0 / total * 100).ToString("F0")}%"; }
        }
        private int femaleCount;
        public int FemaleCount
        {
            get { return femaleCount; }
            set { femaleCount = value; OnPropertyChanged(nameof(FemaleCount)); OnPropertyChanged(nameof(FemalePercent)); }
        }
        public string FemalePercent
        {
            get { return $"{(femaleCount * 1.0 / total * 100).ToString("F0")}%"; }
        }
        public void RefreshData()
        {

            var String_Male_Sex = WPFLocalizeExtension.Engine.LocalizeDictionary.Instance.GetLocalizedObject("String_Male_Sex", null, null) + "";
            var String_Femininity = WPFLocalizeExtension.Engine.LocalizeDictionary.Instance.GetLocalizedObject("String_Femininity", null, null) + "";
            var String_Unknown = WPFLocalizeExtension.Engine.LocalizeDictionary.Instance.GetLocalizedObject("String_Unknown", null, null) + "";

            if (DbStorage.PatientInfos.Count() > 0)
                {
                    imgEmpty.Visibility = Visibility.Collapsed;
                    gridChart.Visibility = Visibility.Visible;
                    chartGender.Visibility = Visibility.Visible;
                }
                else
                {
                    return;
                }
                total = DbStorage.PatientInfos.Count();
                ManCount = DbStorage.PatientInfos.Count(it => it.Sex == SexKind.Male);
                FemaleCount = DbStorage.PatientInfos.Count(it => it.Sex == SexKind.Female);
                int unknowCount = DbStorage.PatientInfos.Count(it => it.Sex ==  SexKind.None);
                if (SeriesCollection == null)
                {
                    SeriesCollection = new SeriesCollection
                    {
                        new PieSeries
                {
                    Title = String_Male_Sex,
                    Values = new ChartValues<ObservableValue> { new ObservableValue(manCount) },
                    DataLabels = false,
                    Fill = new SolidColorBrush(Color.FromRgb(234,194,30))
                },
                new PieSeries
                {
                    Title = String_Femininity,
                    Values = new ChartValues<ObservableValue> { new ObservableValue(femaleCount) },
                    DataLabels = false,
                    Fill = new SolidColorBrush(Color.FromRgb(242,149,43))
                },
                new PieSeries
                {
                    Title = String_Unknown,
                    Values = new ChartValues<ObservableValue> { new ObservableValue(unknowCount) },
                    DataLabels = false,
                    Fill = new SolidColorBrush(Color.FromRgb(202,202,202))
                }
                    };
                }
                else
                {
                    foreach (var series in SeriesCollection)
                    {
                        if (series.Title == String_Male_Sex)
                        {
                            series.Values.Cast<ObservableValue>().ElementAt(0).Value = manCount;
                        }
                        else if (series.Title == String_Femininity)
                        {
                            series.Values.Cast<ObservableValue>().ElementAt(0).Value = femaleCount;
                        }
                        else if (series.Title == String_Unknown)
                        {
                            series.Values.Cast<ObservableValue>().ElementAt(0).Value = unknowCount;
                        }
                    }
                };
            
        }
        public event PropertyChangedEventHandler PropertyChanged;
        private void OnPropertyChanged(string propertyName)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }
        private void chartGender_Loaded(object sender, RoutedEventArgs e)
        {
           
            // 延迟操作的执行，直到控件完全渲染
            this.Dispatcher.BeginInvoke(DispatcherPriority.Background, new Action(() =>
            {
                var animation = new DoubleAnimation
                {
                    From = 0,
                    To = 0.9,
                    Duration = new Duration(TimeSpan.FromSeconds(0.5)),
                    BeginTime = TimeSpan.FromSeconds(0.3)
                };
                var animationShadow = new DoubleAnimation
                {
                    From = 0,
                    To = 0.5,
                    Duration = new Duration(TimeSpan.FromSeconds(0.5)),
                    BeginTime = TimeSpan.FromSeconds(0.3)
                };
                borderMan.BeginAnimation(UIElement.OpacityProperty, animation);
                borderManShadow.BeginAnimation(DropShadowEffect.OpacityProperty, animationShadow);
                borderFemale.BeginAnimation(UIElement.OpacityProperty, animation);
                borderFemaleShadow.BeginAnimation(DropShadowEffect.OpacityProperty, animationShadow);
            }));
        }
    }
}
